package com.ruoyi.web.controller.tool.wxpay;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.*;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.model.*;
import com.jfinal.kit.StrKit;
import com.ruoyi.web.core.utils.AjaxResult;
import com.ruoyi.web.core.utils.H5SceneInfo;
import com.ruoyi.web.core.utils.WxPayBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping({"/wxPay"})
@Controller
/* loaded from: WxPayController.class */ public class WxPayController extends AbstractWxPayApiController {
    private static final String USER_PAYING = "USERPAYING";
    private final        Logger log         = LoggerFactory.getLogger(getClass());
    @Autowired
    WxPayBean wxPayBean;
    private String notifyUrl;
    private String refundNotifyUrl;

    @Override // com.ruoyi.web.controller.tool.wxpay.AbstractWxPayApiController
    public WxPayApiConfig getApiConfig() {
        WxPayApiConfig apiConfig;
        try {
            apiConfig = WxPayApiConfigKit.getApiConfig(this.wxPayBean.getAppId());
        } catch (Exception e) {
            apiConfig = WxPayApiConfig.builder().appId(this.wxPayBean.getAppId()).mchId(this.wxPayBean.getMchId()).partnerKey(this.wxPayBean.getPartnerKey()).certPath(this.wxPayBean.getCertPath()).domain(this.wxPayBean.getDomain()).build();
        }
        this.notifyUrl = apiConfig.getDomain().concat("/wxPay/payNotify");
        this.refundNotifyUrl = apiConfig.getDomain().concat("/wxPay/refundNotify");
        return apiConfig;
    }

    @RequestMapping({""})
    @ResponseBody
    public String index() {
        this.log.info("欢迎使用 IJPay 中的微信支付 -By Javen  <br/><br>  交流群：723992875、864988890");
        this.log.info(this.wxPayBean.toString());
        return "欢迎使用 IJPay 中的微信支付 -By Javen  <br/><br>  交流群：723992875、864988890";
    }

    @GetMapping({"/test"})
    @ResponseBody
    public WxPayBean test() {
        return this.wxPayBean;
    }

    @GetMapping({"/getKey"})
    @ResponseBody
    public String getKey() {
        return WxPayApi.getSignKey(this.wxPayBean.getMchId(), this.wxPayBean.getPartnerKey(), SignType.MD5);
    }

    @RequestMapping(value = {"/wapPay"}, method = {RequestMethod.POST, RequestMethod.GET})
    public void wapPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        H5SceneInfo    sceneInfo = new H5SceneInfo();
        H5SceneInfo.H5 h5_info   = new H5SceneInfo.H5();
        h5_info.setType("Wap");
        h5_info.setWap_url("https://gitee.com/javen205/IJPay");
        h5_info.setWap_name("IJPay VIP 充值");
        sceneInfo.setH5Info(h5_info);
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        String         xmlResult      = WxPayApi.pushOrder(false, UnifiedOrderModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).body("IJPay 让支付触手可及-H5支付").attach("Node.js 版:https://gitee.com/javen205/TNWX").out_trade_no(WxPayKit.generateStr()).total_fee("1000").spbill_create_ip(ip).notify_url(this.notifyUrl).trade_type(TradeType.MWEB.getTradeType()).scene_info(JSON.toJSONString(sceneInfo)).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
        this.log.info(xmlResult);
        Map<String, String> result      = WxPayKit.xmlToMap(xmlResult);
        String              return_code = result.get("return_code");
        String              return_msg  = result.get("return_msg");
        if (!WxPayKit.codeIsOk(return_code)) {
            throw new RuntimeException(return_msg);
        }
        else if (!WxPayKit.codeIsOk(result.get("result_code"))) {
            throw new RuntimeException(return_msg);
        }
        else {
            String prepayId = result.get("prepay_id");
            String webUrl   = result.get("mweb_url");
            this.log.info("prepay_id:" + prepayId + " mweb_url:" + webUrl);
            response.sendRedirect(webUrl);
        }
    }

    @RequestMapping(value = {"/webPay"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult webPay(HttpServletRequest request, @RequestParam("total_fee") String totalFee) {
        String openId = (String) request.getSession().getAttribute("openId");
        if (openId == null) {
            openId = "11111111";
        }
        if (StrUtil.isEmpty(openId)) {
            return new AjaxResult().addError("openId is null");
        }
        if (StrUtil.isEmpty(totalFee)) {
            return new AjaxResult().addError("请输入数字金额");
        }
        String ip = IpKit.getRealIp(request);
        if (StrUtil.isEmpty(ip)) {
            ip = "127.0.0.1";
        }
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        String         xmlResult      = WxPayApi.pushOrder(false, UnifiedOrderModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).body("IJPay 让支付触手可及-公众号支付").attach("Node.js 版:https://gitee.com/javen205/TNWX").out_trade_no(WxPayKit.generateStr()).total_fee("1000").spbill_create_ip(ip).notify_url(this.notifyUrl).trade_type(TradeType.JSAPI.getTradeType()).openid(openId).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
        this.log.info(xmlResult);
        Map<String, String> resultMap  = WxPayKit.xmlToMap(xmlResult);
        String              returnCode = resultMap.get("return_code");
        String              returnMsg  = resultMap.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            return new AjaxResult().addError(returnMsg);
        }
        if (!WxPayKit.codeIsOk(resultMap.get("result_code"))) {
            return new AjaxResult().addError(returnMsg);
        }
        return new AjaxResult().success(JSON.toJSONString(WxPayKit.prepayIdCreateSign(resultMap.get("prepay_id"), wxPayApiConfig.getAppId(), wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256)));
    }

    @RequestMapping(value = {"/scanCode1"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult scanCode1(HttpServletRequest request, HttpServletResponse response, @RequestParam("productId") String productId) {
        try {
            if (StrKit.isBlank(productId)) {
                return new AjaxResult().addError("productId is null");
            }
            WxPayApiConfig config    = WxPayApiConfigKit.getWxPayApiConfig();
            String         qrCodeUrl = WxPayKit.bizPayUrl(config.getPartnerKey(), config.getAppId(), config.getMchId(), productId);
            this.log.info(qrCodeUrl);
            this.log.info(ResourceUtils.getURL("classpath:").getPath());
            if (QrCodeKit.encode(qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200, ResourceUtils.getURL("classpath:").getPath().concat("static").concat(File.separator).concat("payQRCode1.png"))) {
                return new AjaxResult().success("payQRCode1.png");
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().addError("系统异常：" + e.getMessage());
        }
    }

    @RequestMapping(value = {"/scanCodeNotify"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String scanCodeNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String result = HttpKit.readData(request);
            this.log.info("scanCodeNotify>>>" + result);
            Map<String, String> map = WxPayKit.xmlToMap(result);
            for (String key : map.keySet()) {
                this.log.info("key= " + key + " and value= " + map.get(key));
            }
            String              appId         = map.get("appid");
            String              openId        = map.get("openid");
            String              mchId         = map.get("mch_id");
            String              isSubscribe   = map.get("is_subscribe");
            String              nonceStr      = map.get("nonce_str");
            String              productId     = map.get("product_id");
            String              sign          = map.get("sign");
            Map<String, String> packageParams = new HashMap<>(6);
            packageParams.put("appid", appId);
            packageParams.put("openid", openId);
            packageParams.put("mch_id", mchId);
            packageParams.put("is_subscribe", isSubscribe);
            packageParams.put("nonce_str", nonceStr);
            packageParams.put("product_id", productId);
            WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            String         packageSign    = WxPayKit.createSign(packageParams, wxPayApiConfig.getPartnerKey(), SignType.MD5);
            String         ip             = IpKit.getRealIp(request);
            if (StrKit.isBlank(ip)) {
                ip = "127.0.0.1";
            }
            String xmlResult = WxPayApi.pushOrder(false, UnifiedOrderModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).body("IJPay 让支付触手可及-扫码支付模式一").attach("Node.js 版:https://gitee.com/javen205/TNWX").out_trade_no(WxPayKit.generateStr()).total_fee("1").spbill_create_ip(ip).notify_url(this.notifyUrl).trade_type(TradeType.NATIVE.getTradeType()).openid(openId).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
            this.log.info("统一下单:" + xmlResult);
            Map<String, String> payResult  = WxPayKit.xmlToMap(xmlResult);
            String              returnCode = payResult.get("return_code");
            String              resultCode = payResult.get("result_code");
            if (!WxPayKit.codeIsOk(returnCode) || !WxPayKit.codeIsOk(resultCode)) {
                return null;
            }
            String              prepayId     = payResult.get("prepay_id");
            Map<String, String> prepayParams = new HashMap<>(10);
            prepayParams.put("return_code", "SUCCESS");
            prepayParams.put("appid", appId);
            prepayParams.put("mch_id", mchId);
            prepayParams.put("nonce_str", System.currentTimeMillis() + "");
            prepayParams.put("prepay_id", prepayId);
            if (sign.equals(packageSign)) {
                prepayParams.put("result_code", "SUCCESS");
            }
            else {
                prepayParams.put("result_code", "FAIL");
                prepayParams.put("err_code_des", "订单失效");
            }
            prepayParams.put("sign", WxPayKit.createSign(prepayParams, wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
            String xml = WxPayKit.toXml(prepayParams);
            this.log.error(xml);
            return xml;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = {"/scanCode2"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult scanCode2(HttpServletRequest request, HttpServletResponse response, @RequestParam("total_fee") String totalFee) {
        if (StrKit.isBlank(totalFee)) {
            return new AjaxResult().addError("支付金额不能为空");
        }
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        String         xmlResult      = WxPayApi.pushOrder(false, UnifiedOrderModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).body("IJPay 让支付触手可及-扫码支付模式二").attach("Node.js 版:https://gitee.com/javen205/TNWXX").out_trade_no(WxPayKit.generateStr()).total_fee("1").spbill_create_ip(ip).notify_url(this.notifyUrl).trade_type(TradeType.NATIVE.getTradeType()).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
        this.log.info("统一下单:" + xmlResult);
        Map<String, String> result     = WxPayKit.xmlToMap(xmlResult);
        String              returnCode = result.get("return_code");
        String              returnMsg  = result.get("return_msg");
        System.out.println(returnMsg);
        if (!WxPayKit.codeIsOk(returnCode)) {
            return new AjaxResult().addError("error:" + returnMsg);
        }
        if (!WxPayKit.codeIsOk(result.get("result_code"))) {
            return new AjaxResult().addError("error:" + returnMsg);
        }
        if (QrCodeKit.encode(result.get("code_url"), BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200, request.getSession().getServletContext().getRealPath("/") + File.separator + "payQRCode2.png")) {
            return new AjaxResult().success("payQRCode2.png");
        }
        return null;
    }

    @RequestMapping(value = {"/microPay"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult microPay(HttpServletRequest request, HttpServletResponse response) {
        String authCode = request.getParameter("auth_code");
        if (StrKit.isBlank(request.getParameter("total_fee"))) {
            return new AjaxResult().addError("支付金额不能为空");
        }
        if (StrKit.isBlank(authCode)) {
            return new AjaxResult().addError("auth_code参数错误");
        }
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        String         xmlResult      = WxPayApi.microPay(false, MicroPayModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).body("IJPay 让支付触手可及-刷卡支付").attach("Node.js 版:https://gitee.com/javen205/TNWXX").out_trade_no(WxPayKit.generateStr()).total_fee("1").spbill_create_ip(ip).auth_code(authCode).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
        this.log.info("xmlResult:" + xmlResult);
        Map<String, String> result     = WxPayKit.xmlToMap(xmlResult);
        String              returnCode = result.get("return_code");
        String              returnMsg  = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            String errCode = result.get("err_code");
            if (!StrKit.notBlank(errCode) || USER_PAYING.equals(errCode)) {
            }
            this.log.info("提交刷卡支付失败>>" + xmlResult);
            return new AjaxResult().addError(returnMsg);
        }
        else if (WxPayKit.codeIsOk(result.get("result_code"))) {
            return new AjaxResult().success(xmlResult);
        }
        else {
            this.log.info("支付失败>>" + xmlResult);
            return new AjaxResult().addError(result.get("err_code_des"));
        }
    }

    @RequestMapping(value = {"/appPay"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult appPay(HttpServletRequest request) {
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        String         xmlResult      = WxPayApi.pushOrder(false, UnifiedOrderModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).body("IJPay 让支付触手可及-App支付").attach("Node.js 版:https://gitee.com/javen205/TNWXX").out_trade_no(WxPayKit.generateStr()).total_fee("1000").spbill_create_ip(ip).notify_url(this.notifyUrl).trade_type(TradeType.APP.getTradeType()).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
        this.log.info(xmlResult);
        Map<String, String> result     = WxPayKit.xmlToMap(xmlResult);
        String              returnCode = result.get("return_code");
        String              returnMsg  = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            return new AjaxResult().addError(returnMsg);
        }
        if (!WxPayKit.codeIsOk(result.get("result_code"))) {
            return new AjaxResult().addError(returnMsg);
        }
        String jsonStr = JSON.toJSONString(WxPayKit.appPrepayIdCreateSign(wxPayApiConfig.getAppId(), wxPayApiConfig.getMchId(), result.get("prepay_id"), wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
        this.log.info("返回apk的参数:" + jsonStr);
        return new AjaxResult().success(jsonStr);
    }

    @RequestMapping(value = {"/miniAppPay"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult miniAppPay(HttpServletRequest request) {
        String openId = (String) request.getSession().getAttribute("openId");
        String ip     = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        String         xmlResult      = WxPayApi.pushOrder(false, UnifiedOrderModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).body("IJPay 让支付触手可及-小程序支付").attach("Node.js 版:https://gitee.com/javen205/TNWXX").out_trade_no(WxPayKit.generateStr()).total_fee("1000").spbill_create_ip(ip).notify_url(this.notifyUrl).trade_type(TradeType.JSAPI.getTradeType()).openid(openId).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
        this.log.info(xmlResult);
        Map<String, String> result     = WxPayKit.xmlToMap(xmlResult);
        String              returnCode = result.get("return_code");
        String              returnMsg  = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            return new AjaxResult().addError(returnMsg);
        }
        if (!WxPayKit.codeIsOk(result.get("result_code"))) {
            return new AjaxResult().addError(returnMsg);
        }
        String jsonStr = JSON.toJSONString(WxPayKit.miniAppPrepayIdCreateSign(wxPayApiConfig.getAppId(), result.get("prepay_id"), wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
        this.log.info("小程序支付的参数:" + jsonStr);
        return new AjaxResult().success(jsonStr);
    }

    @RequestMapping(value = {"/queryOrder"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String queryOrder(@RequestParam(value = "transactionId", required = false) String transactionId, @RequestParam(value = "outTradeNo", required = false) String outTradeNo) {
        try {
            WxPayApiConfig      wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            Map<String, String> params         = OrderQueryModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).transaction_id(transactionId).out_trade_no(outTradeNo).nonce_str(WxPayKit.generateStr()).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.MD5);
            this.log.info("请求参数：{}", WxPayKit.toXml(params));
            String query = WxPayApi.orderQuery(params);
            this.log.info("查询结果: {}", query);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
            return "系统错误";
        }
    }

    @RequestMapping(value = {"/transfer"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String transfer(HttpServletRequest request, @RequestParam("openId") String openId) {
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        String         transfers      = WxPayApi.transfers(TransferModel.builder().mch_appid(wxPayApiConfig.getAppId()).mchid(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).partner_trade_no(WxPayKit.generateStr()).openid(openId).check_name("NO_CHECK").amount("100").desc("IJPay 让支付触手可及-企业付款").spbill_create_ip(ip).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.MD5, false), wxPayApiConfig.getCertPath(), wxPayApiConfig.getMchId());
        this.log.info("提现结果:" + transfers);
        Map<String, String> map        = WxPayKit.xmlToMap(transfers);
        String              returnCode = map.get("return_code");
        String              resultCode = map.get("result_code");
        if (!WxPayKit.codeIsOk(returnCode) || WxPayKit.codeIsOk(resultCode)) {
        }
        return transfers;
    }

    @RequestMapping(value = {"/transferInfo"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String transferInfo(@RequestParam("partner_trade_no") String partnerTradeNo) {
        try {
            WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            return WxPayApi.getTransferInfo(GetTransferInfoModel.builder().nonce_str(WxPayKit.generateStr()).partner_trade_no(partnerTradeNo).mch_id(wxPayApiConfig.getMchId()).appid(wxPayApiConfig.getAppId()).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.MD5, false), wxPayApiConfig.getCertPath(), wxPayApiConfig.getMchId());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = {"/getPublicKey"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getPublicKey() {
        try {
            WxPayApiConfig      wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            Map<String, String> params         = new HashMap<>(4);
            params.put("mch_id", wxPayApiConfig.getMchId());
            params.put("nonce_str", String.valueOf(System.currentTimeMillis()));
            params.put("sign_type", "MD5");
            params.put("sign", WxPayKit.createSign(params, wxPayApiConfig.getPartnerKey(), SignType.MD5));
            return WxPayApi.getPublicKey(params, wxPayApiConfig.getCertPath(), wxPayApiConfig.getMchId());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = {"/payBank"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String payBank() {
        try {
            WxPayApiConfig      wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            Map<String, String> params         = new HashMap<>(10);
            params.put("mch_id", wxPayApiConfig.getMchId());
            params.put("partner_trade_no", System.currentTimeMillis() + "");
            params.put("nonce_str", System.currentTimeMillis() + "");
            params.put("enc_bank_no", RsaKit.encryptByPublicKeyByWx("银行卡号", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6Bl76IwSvBTiibZ+CNRUA6BfahMshZ0WJpHD1GpmvcQjeN6Yrv6c9eIl6gB4nU3isN7bn+LmoVTpH1gHViaV2YyG/zXj4z4h7r+V+ezesMqqorEg38BCNUHNmhnw4/C0I4gBAQ4x0SJOGnfKGZKR9yzvbkJtvEn732JcEZCbdTZmaxkwlenXvM+mStcJaxBCB/h5xJ5VOF5nDbTPzLphIpzddr3zx/Jxjna9QB1v/YSKYXn+iuwruNUXGCvvxBWaBGKrjOdRTRy9adWOgNmtuYDQJ2YOfG8PtPe06ELKjmr2CfaAGrKKUroyaGvy3qxAV0PlT+UQ4ADSXWt/zl0o5wIDAQAB"));
            params.put("enc_true_name", RsaKit.encryptByPublicKeyByWx("银行卡持有人姓名", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6Bl76IwSvBTiibZ+CNRUA6BfahMshZ0WJpHD1GpmvcQjeN6Yrv6c9eIl6gB4nU3isN7bn+LmoVTpH1gHViaV2YyG/zXj4z4h7r+V+ezesMqqorEg38BCNUHNmhnw4/C0I4gBAQ4x0SJOGnfKGZKR9yzvbkJtvEn732JcEZCbdTZmaxkwlenXvM+mStcJaxBCB/h5xJ5VOF5nDbTPzLphIpzddr3zx/Jxjna9QB1v/YSKYXn+iuwruNUXGCvvxBWaBGKrjOdRTRy9adWOgNmtuYDQJ2YOfG8PtPe06ELKjmr2CfaAGrKKUroyaGvy3qxAV0PlT+UQ4ADSXWt/zl0o5wIDAQAB"));
            params.put("bank_code", "1001");
            params.put("amount", "1");
            params.put("desc", "IJPay 让支付触手可及-付款到银行卡");
            params.put("sign", WxPayKit.createSign(params, wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256));
            return WxPayApi.payBank(params, wxPayApiConfig.getCertPath(), wxPayApiConfig.getMchId());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = {"/queryBank"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String queryBank(@RequestParam("partner_trade_no") String partnerTradeNo) {
        try {
            WxPayApiConfig      wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            Map<String, String> params         = new HashMap<>(4);
            params.put("mch_id", wxPayApiConfig.getMchId());
            params.put("partner_trade_no", partnerTradeNo);
            params.put("nonce_str", System.currentTimeMillis() + "");
            params.put("sign", WxPayKit.createSign(params, wxPayApiConfig.getPartnerKey(), SignType.MD5));
            return WxPayApi.queryBank(params, wxPayApiConfig.getCertPath(), wxPayApiConfig.getMchId());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = {"/profitSharingAddReceiver"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String profitSharingAddReceiver() {
        try {
            Map<String, String> params = ProfitSharingModel.builder().mch_id(this.wxPayBean.getMchId()).appid(this.wxPayBean.getAppId()).nonce_str(WxPayKit.generateStr()).receiver(JSON.toJSONString(ReceiverModel.builder().type("PERSONAL_OPENID").account("openid").relation_type("PARTNER").build())).build().createSign(this.wxPayBean.getPartnerKey(), SignType.HMACSHA256);
            this.log.info("请求参数:{}", WxPayKit.toXml(params));
            String result = WxPayApi.profitSharingAddReceiver(params);
            this.log.info("请求结果:{}", result);
            return JSON.toJSONString(WxPayKit.xmlToMap(result));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = {"/profitSharing"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String profitSharing(@RequestParam("transactionId") String transactionId) {
        List<ReceiverModel> list = new ArrayList<>();
        list.add(ReceiverModel.builder().type("PERSONAL_OPENID").account("openid").amount(66).description("IJPay 分账").build());
        Map<String, String> params = ProfitSharingModel.builder().mch_id(this.wxPayBean.getMchId()).appid(this.wxPayBean.getAppId()).nonce_str(WxPayKit.generateStr()).transaction_id(transactionId).out_order_no(WxPayKit.generateStr()).receivers(JSON.toJSONString(list)).build().createSign(this.wxPayBean.getPartnerKey(), SignType.HMACSHA256);
        this.log.info("请求参数:{}", WxPayKit.toXml(params));
        String result = WxPayApi.profitSharing(params, this.wxPayBean.getCertPath(), this.wxPayBean.getMchId());
        this.log.info("请求结果:{}", result);
        return JSON.toJSONString(WxPayKit.xmlToMap(result));
    }

    @RequestMapping(value = {"/refund"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String refund(@RequestParam(value = "transactionId", required = false) String transactionId, @RequestParam(value = "outTradeNo", required = false) String outTradeNo) {
        try {
            this.log.info("transactionId: {} outTradeNo:{}", transactionId, outTradeNo);
            if (StrKit.isBlank(outTradeNo) && StrKit.isBlank(transactionId)) {
                return "transactionId、out_trade_no二选一";
            }
            WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            String         refundStr      = WxPayApi.orderRefund(false, RefundModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).transaction_id(transactionId).out_trade_no(outTradeNo).out_refund_no(WxPayKit.generateStr()).total_fee("1").refund_fee("1").notify_url(this.refundNotifyUrl).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.MD5), wxPayApiConfig.getCertPath(), wxPayApiConfig.getMchId());
            this.log.info("refundStr: {}", refundStr);
            return refundStr;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = {"/refundQuery"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String refundQuery(@RequestParam("transactionId") String transactionId, @RequestParam("out_trade_no") String outTradeNo, @RequestParam("out_refund_no") String outRefundNo, @RequestParam("refund_id") String refundId) {
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
        return WxPayApi.orderRefundQuery(false, RefundQueryModel.builder().appid(wxPayApiConfig.getAppId()).mch_id(wxPayApiConfig.getMchId()).nonce_str(WxPayKit.generateStr()).transaction_id(transactionId).out_trade_no(outTradeNo).out_refund_no(outRefundNo).refund_id(refundId).build().createSign(wxPayApiConfig.getPartnerKey(), SignType.MD5));
    }

    @RequestMapping(value = {"/refundNotify"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String refundNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        this.log.info("退款通知=" + xmlMsg);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
        if (!WxPayKit.codeIsOk(params.get("return_code"))) {
            return null;
        }
        this.log.info("退款通知解密后的数据=" + WxPayKit.decryptData(params.get("req_info"), WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey()));
        Map<String, String> xml = new HashMap<>(2);
        xml.put("return_code", "SUCCESS");
        xml.put("return_msg", "OK");
        return WxPayKit.toXml(xml);
    }

    @RequestMapping(value = {"/sendRedPack"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String sendRedPack(HttpServletRequest request, @RequestParam("openId") String openId) {
        try {
            String ip = IpKit.getRealIp(request);
            if (StrKit.isBlank(ip)) {
                ip = "127.0.0.1";
            }
            WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            String         result         = WxPayApi.sendRedPack(SendRedPackModel.builder().nonce_str(WxPayKit.generateStr()).mch_billno(WxPayKit.generateStr()).mch_id(wxPayApiConfig.getMchId()).wxappid(wxPayApiConfig.getAppId()).send_name("IJPay 红包测试").re_openid(openId).total_amount("1000").total_num("1").wishing("感谢您使用 IJPay").client_ip(ip).act_name("感恩回馈活动").remark("点 start 送红包，快来抢!").build().createSign(wxPayApiConfig.getPartnerKey(), SignType.MD5), wxPayApiConfig.getCertPath(), wxPayApiConfig.getMchId());
            System.out.println("发送红包结果:" + result);
            return JSON.toJSONString(WxPayKit.xmlToMap(result));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = {"/payNotify"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String payNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        this.log.info("支付通知=" + xmlMsg);
        Map<String, String> params     = WxPayKit.xmlToMap(xmlMsg);
        String              returnCode = params.get("return_code");
        if (!WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256) || !WxPayKit.codeIsOk(returnCode)) {
            return null;
        }
        Map<String, String> xml = new HashMap<>(2);
        xml.put("return_code", "SUCCESS");
        xml.put("return_msg", "OK");
        return WxPayKit.toXml(xml);
    }
}
